<template>
  <PageWrapper contentClass="editLayout" :title="bigTitle" contentBackground>
    <div class="bg-white px-4 py-4 ml-2">
      <BasicForm @register="registerForm" :size="FORM_SIZE" :schemas="ProcessLeftData()">
        <template #basicInfo1>
          <div class="display-flex">
            <div class="w-2 h-4 bg-blue-500 mt-1 mr-2"></div>
            <h1>{{ t('table.member.member_basic1') }}</h1>
          </div>
        </template>
        <template #basicInfo2>
          <div class="display-flex">
            <div class="w-2 h-4 bg-blue-500 mt-1 mr-2"></div>
            <h1>{{ t('table.member.mission_basic2') }}</h1>
          </div>
        </template>
        <template #basicInfo3>
          <div class="display-flex">
            <div class="w-2 h-4 bg-blue-500 mt-1 mr-2"></div>
            <h1>{{ t('table.member.mission_basic3') }}</h1>
          </div>
        </template>
        <template #terminalSlot="{ model, field }">
          <!-- 语言框 -->
          <Row>
            <FormItemRest>
              <Checkbox
                :disabled="toDisabled"
                v-model:checked="openTerminalState.checkAll"
                :indeterminate="openTerminalState.indeterminate"
                @change="onCheckAllChange($event, model, field)"
              >
                {{ t('business.common_select_all') }}
              </Checkbox>
            </FormItemRest>
            <CheckboxGroup
              :disabled="toDisabled"
              v-model:value="openTerminalState.checkedList"
              :options="openTerminalOptions"
              @change="onChangeOpenTerminal($event, model, field)"
            />
          </Row>
        </template>
        <!-- :disabled="toDisabled" -->
        <template #CurrencyConfig="{ model, field }">
          <CurryRadioGroup
            ref="currencyRadioRef"
            :contentList="currenyLang"
            @update:click="changeHandleCurry"
            v-model="model[field]"
            v-model:currencyId="currentCurryId"
          />
        </template>
        <template #task_params>
          <Row>
            <Col :span="24">
              <FormItem>
                <Select
                  :size="FORM_SIZE as any"
                  :disabled="toDisabled"
                  v-model:value="taskActive"
                  :options="taskOptions"
                  @change="changTaskActive"
                  style="height: 40px"
                />
              </FormItem>
            </Col>
          </Row>
        </template>
        <template #buttonTextSlot>
          <Row>
            <Col :span="17">
              <FormItem>
                <Input
                  :disabled="toDisabled"
                  :size="FORM_SIZE as any"
                  :placeholder="$t('v.discount.activity.btnText')"
                  v-model:value="btnText"
                  @change="changInput('LEFT')"
                  @blur="handleTinymceBlurZx('buttonText')"
                  style="height: 40px"
                />
              </FormItem>
            </Col>
            <Col :span="7">
              <Button
                type="primary"
                :disabled="toDisabled"
                :size="FORM_SIZE"
                class="m-l-5"
                @click="handleMoreLagarage"
                >{{ $t('v.discount.activity.more_language') }}</Button
              >
            </Col>
          </Row>
        </template>
        <template #zhNameTextSlot="{ model, field }">
          <Row>
            <Col :span="16">
              <FormItem class="ant-form-item-with-help">
                <Input
                  :size="FORM_SIZE"
                  :placeholder="$t('v.discount.activity.mission_name')"
                  v-model:value="zhText"
                  :disabled="toDisabled || defaultTy == 4 || defaultTy == 5"
                  @change="changInputzhText"
                  @blur="handleTinymceBlurZx"
                  style="height: 40px"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <Button
                type="primary"
                class="m-l-5"
                :disabled="toDisabled || defaultTy == 4 || defaultTy == 5"
                :size="FORM_SIZE"
                @click="handleMoreLagarage('zh_name')"
                >{{ $t('v.discount.activity.more_language') }}</Button
              >
            </Col>
          </Row>
        </template>
        <template #detailTextSlot="{ model, field }">
          <Row>
            <Col :span="16">
              <FormItem>
                <Input
                  :size="Number(FORM_SIZE)"
                  :placeholder="$t('table.discountActivity.task_statement')"
                  v-model:value="detail"
                  :disabled="toDisabled"
                  @change="changInputzhText('detail')"
                  @blur="handleTinymceBlurZx('detailList')"
                  style="height: 40px"
                />
              </FormItem>
            </Col>
            <Col :span="8">
              <Button
                type="primary"
                class="m-l-5"
                :size="FORM_SIZE"
                :disabled="toDisabled"
                @click="handleMoreLagarage('detailList')"
                >{{ $t('v.discount.activity.more_language') }}</Button
              >
            </Col>
          </Row>
        </template>
        <template #NegativeConfigType v-if="platform_range == 2">
          <div class="zyjuz_j">
            <div class="w-70%">
              <div class="">
                <abRoundButtonGroup
                  class="mt-4"
                  :disabled="toDisabled"
                  v-model="tabValue"
                  :blackEdge="true"
                  :btnList="venueList"
                />
              </div>
              <CheckboxGroup
                :disabled="toDisabled"
                class="!mt-10px"
                v-model:value="current_platform_ids"
                style="width: 100%"
              >
                <Row>
                  <Col :span="4" v-for="item in current_game" :key="item.value">
                    <Checkbox
                      @change="handleCheckboxChange($event, item)"
                      :disabled="item.disabled"
                      :value="item.value"
                      >{{ item.name }}</Checkbox
                    >
                  </Col>
                </Row>
              </CheckboxGroup>
            </div>
          </div>
        </template>
        <template #vip="{ model, field }">
          <Space class="space-box">
            <Button
              :disabled="toDisabled"
              :class="{ 'ant-btn-primary': VIPLevelActiveIndex.some((item) => item === +index) }"
              class="w-[53px] h-[36px] mr-5px mb-5px"
              style="padding: 0 !important"
              v-for="(item, index) in allVipConfig"
              :key="index"
              @click="changeVIPLevelActiveIndex(item, index)"
              >{{ 'VIP' + item.level }}</Button
            >
          </Space>
        </template>
        <!-- 表格 -->
        <template #commonTable>
          <commonTable
            ref="commonTable_"
            v-model="currentCurryId"
            :toDisabled="toDisabled"
            :currencyList="currencyList"
            :platform_range="platform_range"
            :current_platform_ids="current_platform_ids"
            :all_platform_ids="all_platform_ids"
            :plateOptions="plateOptions"
            :firstCurrencyId="'CNY'"
            :type="defaultTy"
            :getDeatilId="false"
            :getDeatilId1="Timestamp_before_disabled"
          />
        </template>
      </BasicForm>
    </div>
    <template #rightFooter>
      <a-button
        type="primary"
        :size="FORM_SIZE"
        :disabled="btnloading || toDisabled"
        @click="submitOk"
      >
        {{ $t('common.saveText') }}
      </a-button>
    </template>
    <buttonTextModal @emits-values="emitsValues" @register="textModal" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import {
    reactive,
    watch,
    ref,
    onMounted,
    onBeforeMount,
    onUnmounted,
    nextTick,
    computed,
  } from 'vue';
  import commonTable from '../components/commonTable/index.vue';

  import { PageWrapper } from '/@/components/Page';
  import { useI18n } from '/@/hooks/web/useI18n';
  import buttonTextModal from '@/views/discountActivity/activity/components/insertActiveNew/buttonTextModal.vue';

  import {
    RadioGroup,
    Input,
    FormItem,
    Row,
    Col,
    FormItemRest,
    Switch,
    Upload,
    //Button,
    message,
    CheckboxGroup,
    Checkbox,
    InputNumber,
    Textarea,
    Radio,
    Tooltip,
    Form,
    DatePicker,
    Select,
    SelectOption,
    InputGroup,
    TimePicker,
  } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useFormSetting } from '/@/hooks/setting/useFormSetting';
  import { ProcessLeftData } from './index.data';
  import { useLocalList } from '/@/settings/localeSetting';
  import CurryRadioGroup from '../../activity/components/insertActiveNew/CurryRadioGroup.vue';
  import { Button } from '/@/components/Button/index';
  import { useRouter } from 'vue-router';
  import {
    UpdateMission,
    InsertMission,
    GetMissionDetail,
    getMissionList,
    getMissionCategoryList,
  } from '/@/api/mission';
  import abRoundButtonGroup from '/@/components/abRoundButtonGroup/ab-round-button-group.vue';
  import { useGameSortStore } from '/@/store/modules/gameSort';
  import { useSystemStore } from '/@/store/modules/system';
  import { useModal } from '/@/components/Modal';
  import { useLocale } from '/@/locales/useLocale';
  import dayjs from 'dayjs';
  import translateContentList from '/@/views/common/language';
  import { LangItem } from '/@/views/system/informationCenter/common/setting';
  import eventBus from '/@/utils/eventBus';
  import { getMemberRebateConfig } from '/@/api/member';

  const $router = useRouter();
  const { t } = useI18n();
  const clientList = ref([]);
  const selectList = ref([]);
  const currencyName = ref('CNY');

  const commonTable_ = ref();
  const VIPLevelActiveIndex = ref([0]);
  const allVipConfig = ref<Record<string, any>>([]);
  const tabValue = ref<string>('1');
  const detail = ref('');
  const detailList = ref({ zh_CN: '' });
  const zhText = ref<any>(null);
  const btnLange: any = ref({});
  const btnText: any = ref(null);
  const zxLange: any = ref({});
  const btnloading = ref(false);
  const Timestamp_before_disabled = ref(false);
  const defaultTy = ref<any>(1);
  const systemCurrency = ref('');

  const localeList = useLocalList();
  const bigTitle = ref(t('v.discount.mission_add'));
  const FORM_SIZE = useFormSetting().getFormSize || 23;

  const langList: any = ref<any[]>([]);

  /** 所有语言：['zh_CN', 'en_US', 'vi_VN', 'pt_BR', 'th_TH', 'hi_IN'] */
  let openLangOptions: Array<any> = [];
  const currentCurryId = ref('701' as string);
  const getDeatilId = ref('' as any);
  const gameSortStore = useGameSortStore();
  const systemStore = useSystemStore();
  const syslang = useLocale().getLocale.value;
  const disabledType = ref(false as any);

  const currencyList = [
    {
      label: 'CNY',
      value: '701',
      lang: 'zh_CN',
    },
    {
      label: 'BRL',
      value: '702',
      lang: 'pt_BR',
    },
    {
      label: 'KVND',
      value: '704',
      lang: 'vi_VN',
    },

    {
      label: 'THB',
      value: '705',
      lang: 'th_TH',
    },

    {
      label: 'INR',
      value: '703',
      lang: 'hi_IN',
    },

    {
      label: 'USDT',
      value: '706',
      lang: 'en_US',
    },
  ];
  const currenyLang = ref(currencyList);
  const taskActive = ref<any>(null);
  const taskOptions = ref<any>([]);
  let historyData = {};
  try {
    historyData = JSON.parse(history.state.data);
  } catch (e) {
    console.log('e', e);
  }
  // const toDisabled = false;
  const toDisabled = history.state.type == 3 || historyData.state == 2;

  const currencyNameList_award = ref({
    '701': { award: '' },
    '702': { award: '' },
    '704': { award: '' },
    '705': { award: '' },
    '703': { award: '' },
    '706': { award: '' },
  });

  onBeforeMount(async () => {
    //编辑
    if (history.state.id) {
      await gameSortStore.setgame_typeList();
      getEditData().then(async () => {
        info_venue();
      });
      // handleClickContent(1, { event: 'zh_CN' });
      disabledType.value = true;
      bigTitle.value = t('v.discount.activity_editor1');
      if (toDisabled) {
        bigTitle.value = t('v.discount.activity_check1');
      }
    } else {
      await gameSortStore.setgame_typeList().then(() => {
        info_venue();
      }); //调用游戏类型接口
      await getMissionCategoryList_();
    }
    const allConfig = await getMemberRebateConfig();
    allVipConfig.value = allConfig.vip;
  });
  function changeVIPLevelActiveIndex(item, index) {
    if (VIPLevelActiveIndex.value.some((item) => item == index)) {
      VIPLevelActiveIndex.value = VIPLevelActiveIndex.value.filter((item) => item != index);
    } else {
      VIPLevelActiveIndex.value.push(index);
    }
    // VIPLevelActiveIndex.value = [...new Set(VIPLevelActiveIndex.value)];
    console.log('VIPLevelActiveIndex.value', VIPLevelActiveIndex.value);
  }
  // 初始化语言列表
  function initLangList() {
    langList.value = localeList.map((item: any) => {
      openLangOptions.push(item.event);
      return {
        label: t('common.common_' + item.event),
        value: item.event,
        language: item.language || '',
      };
    });
  }
  // 立即初始化语言列表
  initLangList();
  // 更新值，写在最下方生命周期
  async function updateValidList() {
    const res = await systemStore.getValidLangList();
    systemCurrency.value = res;
    openLangOptions = [];

    // console.log(111113343,localeList);
    console.log(res);
    langList.value = localeList
      .filter((lang) => res && res.includes(lang.event))
      .map((item) => {
        openLangOptions.push(item.event);
        btnLange.value[item.event] = null;
        zxLange.value[item.event] = null;
        // const textContent = ref(getTextData(defaultTy.value)[item.event]);
        return {
          label: t('common.common_' + item.event),
          value: item.event,
          transitionValue: '',
          image_url: '',
          language: item.language || '',
          phoneData: '',
          // textContent: getTextData(defaultTy.value)[item.event],
          zxTransitionValue: '',
          btnTransitionValue: '',
          // textContent:textContent.value,
        };
      });
    if (Array.isArray(res)) {
      openTerminalState.checkedList = openLangOptions;
    }
    if (typeof res === 'string') {
      openTerminalState.checkedList = [res];
      console.log(openTerminalState.checkedList, 'openTerminalState');
    }
    openTerminalOptions.value = langList.value;
  }

  const openTerminalState = reactive({
    indeterminate: false,
    checkAll: true,
    checkedList: openLangOptions,
  });

  const openTerminalOptions = ref(langList.value);
  const contentList: any = ref<Array<LangItem>>([...langList.value]);
  const currentLang = ref(contentList.value[0]);

  const [
    registerForm,
    {
      validate: leftValue,
      setFieldsValue: setFieldsValueLeft,
      updateSchema,
      getFieldsValue,
      clearValidate,
    },
  ] = useForm({
    disabled: toDisabled,
    labelWidth: 120,
    baseColProps: {
      span: 24,
    },
    showActionButtonGroup: false,
  });

  const getMissionCategoryList_ = async () => {
    const d = await getMissionCategoryList({ page: 1, page_size: 251 });
    // .then(({ d }) => {
    const data = d.d?.map(({ category_name, id }) => {
      const currency_name = currencyList.find(
        (currency) => currency.value == currentCurryId.value,
      )?.lang;
      let label_name;
      if (currency_name) {
        try {
          label_name = JSON.parse(category_name)[currency_name];
        } catch (e) {
          label_name = category_name;
          console.log(111, e);
        }
      }
      // console.log('category_name111', category_name, label_name, currency_name);
      return {
        category_name: category_name,
        label: label_name,
        value: id,
      };
    });
    if (updateSchema) {
      // console.log('111223data', data);
      updateSchema({
        field: 'cate_id',
        componentProps: ({ formModel }) => {
          return {
            onChange: (e, option) => {
              // console.log('e111', e, option, formModel);
              formModel.cate_name = option.category_name;
            },
            options: data,
          };
        },
      });
    }
    // });
  };
  // getMissionCategoryList_();

  function changTaskActive(value) {
    taskActive.value = value;
    let itemActive = taskOptions.value.filter((item) => item.value == value);
    getEditData(itemActive[0].itemData);
    console.log('taskActive.value', value, itemActive[0].itemData, taskActive.value);
  }

  let plateOptions: any = [];

  const currentTimestamp = Date.now();
  async function getEditData(itemData?) {
    // const data = await GetMissionDetail({ pid: history.state.id });
    let data = itemData || {};
    let config: any = {};
    try {
      if (!itemData) {
        data = JSON.parse(history.state.data);
        config = JSON.parse(data.config);
        getDeatilId.value = data.id;
      } else {
        data = itemData;
        config = JSON.parse(itemData.config);
      }
    } catch (e) {
      console.log('e', e);
    }
    console.log('data111', data);
    console.log('config111', config);

    defaultTy.value = data.ty;
    if (new Date(data.start_at_tz).getTime() < currentTimestamp) {
      Timestamp_before_disabled.value = true;
    } else {
      Timestamp_before_disabled.value = false;
    }

    if (JSON.parse(data.detail).zh_CN) detailList.value = JSON.parse(data.detail);
    if (JSON.parse(data.button).zh_CN) btnLange.value = JSON.parse(data.button);
    if (JSON.parse(data.names).zh_CN) zxLange.value = JSON.parse(data.names);

    contentList.value.forEach((item) => {
      item.detailList = detailList.value[item.value] || '';
      item.zxTransitionValue = zxLange.value[item.value];
      item.btnTransitionValue = btnLange.value[item.value];
    });
    // console.log('zxLange.value ', zxLange.value);
    // console.log('btnLange.value ', btnLange.value);
    // console.log('detailList.value ', detailList.value);
    // console.log('contentList.value', contentList.value);
    zhText.value = JSON.parse(data.names)['zh_CN'];
    detail.value = JSON.parse(data.detail)['zh_CN'];

    if (btnLange.value.hasOwnProperty(syslang)) {
      btnText.value = btnLange.value[syslang];
      setFieldsValueLeft({ button: btnText.value });
    }
    // 币种处理
    if (Array.isArray(systemCurrency.value)) {
      openTerminalState.checkedList = JSON.parse(data.lang);
    } else {
      openTerminalState.checkedList = [systemCurrency.value];
    }
    currenyLang.value = filterHandleCurry(openTerminalState.checkedList);
    currentCurryId.value = currenyLang.value[0]?.value || '701';
    let tongue = config.tongue || {};
    currencyNameList_award.value = tongue;
    // console.log('tongue', tongue['701']);

    await setFieldsValueLeft({
      ...data,
      award: tongue[currentCurryId.value]?.award || '',
      // audit: tongue['701']?.audit || '',
      button: btnLange.value?.zh_CN || '1',
      detail: detailList.value?.zh_CN || '1',
      names: zxLange.value?.zh_CN || '1',
      lang: JSON.parse(data.lang),
      time: [dayjs(data.start_at_tz || data.start_at), dayjs(data.end_at_tz || data.end_at)],
      // currency_id: data.currency_id,
      // display_type: Number(data.display_type),
      // rule_type: data.rule_type,
    });
    getMissionCategoryList_();

    setContentList();
    handleConfig(data);

    setTimeout(() => {
      let tableData = commonTable_.value?.conditionData;
      // let conditionData2 = commonTable_.value?.conditionData2;
      // let conditionData3 = commonTable_.value?.conditionData3;
      // console.log('tableData', tableData);
      if ((data.ty === 4 || data.ty === 5) && commonTable_.value?.conditionData) {
        // info_venue();
        async function transformTableData(lang: string, id?: any) {
          // tableData[lang].bonus_serial.sort((a, b) => a.day - b.day);
          if (data.ty === 4) {
            // tableData[lang].forEach((item, index, arr) => {
            //   item.index = Number(item.index);
            //   const { deposit, award } = item;
            // console.log('config.tongue[lang]?.deposit', lang, id, config.tongue[id]);
            // });
            tableData[lang] = config.tongue[id]?.deposit;
          } else {
            platform_ids.value = Object.values(config.assign_sport).flat();
            info_venue();
            await setFieldsValueLeft({
              platform_range: config.sport,
            });
            let configuration: any = Object.keys(config.way[id]).includes('0');
            configuration = configuration ? 1 : 2;

            // console.log('configuration111', configuration);
            setFieldsValueLeft({
              configuration: configuration,
            });
            if (configuration == 2) {
              commonTable_.value.conditionData2[id] = config.way[id];
              // console.log('config.way[id] 111', config.way[id]);
              // console.log(
              //   'conditionData2 111',
              //   id,
              //   commonTable_.value.conditionData2[id],
              //   commonTable_.value?.conditionData2,
              // );
            } else {
              tableData[lang] = config.way[id]['0'];
            }
          }
          return tableData[lang];
        }
        let res = openTerminalState.checkedList.reduce<any>((langObj, lang) => {
          const langToValue = currencyList.filter((currency) => currency.lang == lang);
          langObj[langToValue[0].value] = transformTableData(lang, langToValue[0].value);
          return langObj;
        }, {});
        // console.log('openTerminalState.checkedList111', openTerminalState.checkedList, res);

        if (data.ty === 4) {
          VIPLevelActiveIndex.value = config.vip;
          console.log('tableData', tableData, config);
        } else if (data.ty === 5) {
          // tableData = config.way;
          commonTable_.value.conditionData3 = config.tongue;
          VIPLevelActiveIndex.value = config.vip;
        }
      }
    }, 111);
  }

  async function submitOk() {
    const leftValues = await leftValue();
    console.log('leftValues111 ', leftValues);
    // console.log(' zxLange.value ', zxLange.value);

    // 先注释校验
    // const isValid = await validateBeforeSubmit(leftValues);
    // if (!isValid) {
    //   return false;
    // }
    // btnloading.value = true;
    const {
      names,
      ty,
      cate_id,
      state,
      job_duration_type,
      multiple,
      cycle,
      automatic,
      withdraw_type,
      button,
      button_type,
      button_redirect,
      lang,
      detail,
      device,
      vip,
      cate_name,
      award,
      validate_type,
      audit,
    } = leftValues;

    let tableData = commonTable_.value?.conditionData;
    let tableData2 = commonTable_.value?.conditionData2;
    let conditionData3 = commonTable_.value?.conditionData3;

    // console.log('tableData', tableData);
    // console.log('tableData2', tableData2);
    // console.log('conditionData3', conditionData3);

    let conditionVerify = true;

    let transformTableData = (lang: string, id?: any) => {
      let data: any;
      const langName = currencyList.filter((item) => item.lang == lang)[0].label;

      if (leftValues.ty == 4) {
        // tableData[lang].bonus_serial.sort((a, b) => a.day - b.day);
        tableData[lang].forEach((item, index, arr) => {
          // item.index = Number(item.index);
          const { deposit, award } = item;
          if (!deposit || !award) {
            console.log(111, '基础配置信息', award, deposit);
            // // 使用 message 提示
            message.error(`请填写完整${langName}配置信息`);
            conditionVerify = false;
            // arr.splice(index, 1);
          }
        });
        if (conditionVerify) {
          data = { deposit: [...tableData[lang]] };
        }
      } else if (leftValues.ty == 5) {
        if (!conditionData3[id].sales) {
          conditionVerify = false;
          message.error(`请填写完整${langName}返水上限配置信息`);
        }
        // console.log('leftValues.configuration', conditionData3[id], leftValues.configuration);

        if (leftValues.configuration == 1 || !leftValues.configuration) {
          tableData[lang].forEach((item, index, arr) => {
            // item.index = Number(item.index);
            const { coding, sales_rate } = item;
            if (!coding || !sales_rate) {
              console.log(111, '基础配置信息', coding, sales_rate);
              const langName = currencyList.filter((item) => item.lang == lang)[0].label;
              // // 使用 message 提示
              message.error(`请填写完整${langName}配置信息`);
              conditionVerify = false;
              // arr.splice(index, 1);
            }
          });
        } else {
          //
          for (let key in tableData2[id]) {
            if (tableData2[id].hasOwnProperty(key)) {
              // 使用hasOwnProperty确保只遍历自身的属性
              // console.log(key, tableData2[id][key]);

              tableData2[id][key].forEach((item, index, arr) => {
                // item.index = Number(item.index);
                const { coding, sales_rate } = item;
                if (!coding || !sales_rate) {
                  console.log(111, '基础配置信息', coding, sales_rate);
                  const langName = currencyList.filter((item) => item.lang == lang)[0].label;
                  // // 使用 message 提示
                  message.error(`请填写完整${langName}配置信息`);
                  conditionVerify = false;
                  // arr.splice(index, 1);
                }
              });
            }
          }
        }
      } else {
        // console.log('111', currencyNameList_award.value[id].award);
        // console.log('111', !!!currencyNameList_award.value[id].award.trim());
        if (!currencyNameList_award.value[id]?.award.trim()) {
          conditionVerify = false;
          message.error(`请填写完整${langName}奖励金额信息`);
        }
        if (conditionVerify) {
          data = currencyNameList_award.value[id];
        }
      }

      return data;
    };

    let res = openTerminalState.checkedList.reduce<any>((langObj, lang) => {
      const langToValue = currencyList.filter((currency) => currency.lang == lang);
      langObj[langToValue[0].value] = transformTableData(lang, langToValue[0].value);
      return langObj;
    }, {});
    console.log('res', res, conditionVerify);

    if (!conditionVerify) return;

    let config: any = {
      device, // 同注册设备号限制
      tongue: { ...res },
      // {
      //   '701': {
      //     award, // 奖励金额
      //   },
      // },
    };
    if (leftValues.ty === 4 || leftValues.ty === 5) {
      if (leftValues.ty === 4) {
        config = {
          vip: VIPLevelActiveIndex.value,
          tongue: {
            ...res,
          },
        };
      } else {
        let assign_sport = {};
        let tongue = {};
        let newVal = plateOptions.map((item) => item.value);

        venueList.value.forEach((item) => {
          if (platform_range.value == 1) {
            // assign_sport[item.value] = item.allVen.map((el) => el.value);
          } else {
            if (item.appointVen.map((el) => el.value).length) {
              assign_sport[item.value] = item.appointVen.map((el) => el.value);
            }
          }
        });
        // console.log('assign_sport', assign_sport);
        let way = {};

        res = openTerminalState.checkedList.reduce<any>((langObj, lang) => {
          const langToValue = currencyList.filter((currency) => currency.lang == lang);
          langObj[langToValue[0].value] = lang;

          tongue[langToValue[0].value] = {};
          tongue[langToValue[0].value].sales = conditionData3[langToValue[0].value].sales;

          if (leftValues.configuration == 1 || !leftValues.configuration) {
            way[langToValue[0].value] = {
              '0': tableData[lang].map((element1) => {
                return {
                  coding: element1.coding, // 有效打码
                  sales_rate: element1.sales_rate, // 反水率
                };
              }),
            };

            // let list = currencyList;
            // list.forEach((item) => {
            //   way[item.value] = {};
            //   // conditionData3.value[item.value] = {
            //   //   sales: '', // 反水上限
            //   // };
            //   newVal.forEach((element) => {
            //     tableData[item.lang].forEach((element1) => {
            //       way[item.value][element] = [
            //         {
            //           coding: element1.coding, // 有效打码
            //           sales_rate: element1.sales_rate, // 反水率
            //         },
            //       ];
            //     });
            //   });
            // });
          } else {
            way[langToValue[0].value] = tableData2[langToValue[0].value];
          }

          return langObj;
        }, {});

        config = {
          vip: VIPLevelActiveIndex.value,
          sport: platform_range.value, // 统计场馆 1全部场馆 2指定场馆
          assign_sport: assign_sport,
          way: platform_range.value == 1 ? way : way,
          tongue: tongue,
        };
      }
    }
    console.log('config', config);

    // return;
    // const { en_US, hi_IN, pt_BR, th_TH, vi_VN, zh_CN } = zxLange.value;
    // zxLange.value.zh_CN = names;
    const data_ = {
      ...leftValues,
      // validate_type,
      id: getDeatilId.value ? getDeatilId.value : '',
      //名称多语言
      names: JSON.stringify(zxLange.value),
      ty, //任务类型：1.注册, 2.下载, 3.验证, 4.存款, 5.投注
      cate_name: cate_name || '-', //分类关联 sg_job_category.id（例如新手任务, KYC验证）
      cate_id, //分类关联 sg_job_category.id（例如新手任务, KYC验证）
      state: getDeatilId.value ? Number(state) : 1, //状态：1.未开始, 2.进行中, 3.已关闭, 4.删除
      job_duration_type, //任务时间类型：1.长期, 2.指定时间范围
      start_at_tz:
        // job_duration_type == 2
        // ? leftValues.time[0].format('YYYY-MM-DD 00:00:00')
        // : dayjs().startOf('day'), //开始时间（时间戳）
        leftValues.time[0].format('YYYY-MM-DD 00:00:00'),
      end_at_tz:
        // job_duration_type == 2
        //   ? leftValues.time[1].format('YYYY-MM-DD 23:59:59')
        //   : dayjs().startOf('day').add(10, 'year'), //结束时间（时间戳）
        leftValues.time[1].format('YYYY-MM-DD 23:59:59'), //结束时间（时间戳）
      multiple: multiple, //流水倍数
      cycle, //循环类型：1.每日循环, 2.每周循环, 3.每月循环
      automatic: 0, //领取方式：1.自动, 2.手动领取
      withdraw_type: 0, //提取方式：1.直接转入钱包, 2.需审核
      config: JSON.stringify(config), //动态配置信息
      images: '{}', //图片多语言
      //按钮文案多语言
      button: JSON.stringify(btnLange.value),
      button_redirect,
      button_type, //跳转类型：1.自定义, 2.娱乐城, 3.体育, 4.保险库, 5.VIP界面, ...
      detail: JSON.stringify(detailList.value), //活动详情介绍多语言
      lang: JSON.stringify(lang), //多语言
    };
    console.log('111 data_', data_);

    const { status, data } = getDeatilId.value
      ? await UpdateMission(data_)
      : await InsertMission(data_);

    if (status) {
      btnloading.value = false;
      message.success(data);
      $router.push({ name: 'mission_list' });
    } else {
      btnloading.value = false;
      message.error(data);
    }
    if (data.ty === 4 || data.ty === 5) {
      // openTerminalState.checkedList.reduce<any>((langObj, lang) => {
      //   const langToValue = currencyList.filter((currency) => currency.lang == lang);
      //   langObj[langToValue[0].value] = transformTableData(lang, 1);
      // }, {});
    }
  }

  async function handleConfig(data) {
    const ty = data.ty;
    // setFieldsValueLeft({
    //   audit: JSON.parse(data.names)['zh_CN'],
    // });
  }
  let assign_sportList: any = [];

  function getMissionListData() {
    return getMissionList({
      page: '1',
      page_size: '100',
      state: '2',
      ty: 5,
      lang: syslang,
    }).then((data) => {
      taskOptions.value = data.d?.map((item) => {
        return {
          label: JSON.parse(item.names)['zh_CN'],
          value: item.id,
          itemData: item,
          config: item.config,
        };
      });
      // console.log('taskOptions111', data, taskOptions.value);
      try {
        assign_sportList = taskOptions.value
          .map((list) => JSON.parse(list.config))
          ?.map((item) => item.assign_sport);
        assign_sportList = assign_sportList?.map((item) => {
          return Object.values(item);
        });
      } catch (e) {
        console.log('e111', e);
        assign_sportList = [];
      }
      assign_sportList = assign_sportList?.flat(Infinity);
      console.log('111 assign_sportList ', assign_sportList);
    });
  }
  getMissionListData();

  const platform_ids = ref<any>([]);

  const venueList: any = ref([
    {
      label: '老虎机',
      value: '1',
      id: '',
      list: [
        { name: 'pg', state: 1 },
        { name: 'pp', state: 2 },
        { name: 'pp1', state: 1 },
      ],
    },
  ]);
  const info_venue = async () => {
    // console.log('111 assign_sportList 2222', assign_sportList);
    if (!assign_sportList.length) await getMissionListData();
    plateOptions = [];
    let { getPlatformList, getgame_typeList } = useGameSortStore();
    for (const key in getPlatformList) {
      plateOptions.push(...(getPlatformList[key] as any));
    }
    plateOptions =
      plateOptions &&
      plateOptions.map((item: any) => {
        return {
          ...item,
          label: item.platform_name,
          name: item.platform_name,
          value: item.platform_id,
          disabled: assign_sportList.includes(item.platform_id),
          state: platform_ids.value.some((el) => el == item.platform_id) ? 1 : 2,
        };
      });
    getgame_typeList = getgame_typeList.filter((item: any) => {
      return item.name != '全部' && item.game_type != '6';
    });
    // console.log(111, plateOptions);
    // console.log(111, getgame_typeList);

    let list: any = [];
    getgame_typeList.forEach((element: any) => {
      list.push({
        label: element.name,
        value: element.game_type,
        id: '',
        list: plateOptions.filter((item) => item.game_type == element.game_type),
        allVen: plateOptions
          .filter((item) => item.game_type == element.game_type)
          .map((el) => {
            return {
              name: el.name,
              value: el.value,
              disabled: el.disabled,
            };
          }),
        appointVen: plateOptions
          .filter((item) => item.game_type == element.game_type)
          .filter((obj) => obj.state === 1)
          .map((el) => {
            return {
              name: el.name,
              value: el.value,
              disabled: el.disabled,
            };
          }),
      });
    });
    venueList.value = list;
    setFieldsValueLeft({ incentiveConfig: 1 });
    // console.log(11121111111, venueList.value, platform_ids.value);
  };
  const Venue_statistics = ref('allVen');
  const platform_range: any = ref(1);

  const current_game: any = computed(() => {
    let list = venueList.value.filter((item) => item.value == tabValue.value)[0].list;
    list = list?.map((item) => {
      return {
        ...item,
        // disabled: item.state == 1 ? false : item.disabled,
        disabled: false,
      };
    });
    // console.log('list111', list);
    return list;
  });
  // const current_game: any = ref([]);
  // watch(
  //   () => venueList.value,
  //   (newV) => {
  //     handleTab();
  //   },
  //   {
  //     deep: true,
  //   },
  // );
  // watch(
  //   () => tabValue.value,
  //   (newV) => {
  //     handleTab();
  //   },
  // );
  // function handleTab() {
  //   let list = venueList.value.filter((item) => item.value == tabValue.value)[0].list;
  //   list = list?.map((item) => {
  //     return {
  //       ...item,
  //       // disabled: item.state == 1 ? false : item.disabled,
  //       disabled: false,
  //     };
  //   });
  //   // console.log('list111', list);
  //   current_game.value = list;
  // }
  const current_platform_ids: any = computed(() => {
    let list =
      (venueList.value.filter((item) => item.value == tabValue.value)[0]?.allVen &&
        venueList.value
          .filter((item) => item.value == tabValue.value)[0]
          [Venue_statistics.value].map((el) => {
            return el.value;
          })) ||
      [];
    return list;
  });
  const all_platform_ids: any = computed(() => {
    let list = venueList.value
      .map((item) => item[Venue_statistics.value]?.map((el) => el.value))
      .flat();
    return list;
  });

  eventBus.on('change_Venue_statistics', (v: any) => {
    if (v !== 'getself') platform_range.value = v;
    platform_range.value == 1
      ? (Venue_statistics.value = 'allVen')
      : (Venue_statistics.value = 'appointVen');
    if (v == 1) {
      setFieldsValueLeft({
        configuration: 1,
      });
    }
    // if (defaultTy.value == 7) changTextData(7);
  });
  const incentiveConfig = ref(1);
  eventBus.on('incentiveConfig', (v: any) => {
    if (v !== 'getself') incentiveConfig.value = v;
  });
  const handleCheckboxChange = (e, item) => {
    setTimeout(() => {
      item.state = e.target?.checked ? 1 : 2;
      item.disabled = false;
      venueList.value
        .filter((item) => item.value == tabValue.value)[0]
        .list.filter((o) => o.platform_id == item.platform_id)[0].state = item.state;
      venueList.value
        .filter((item) => item.value == tabValue.value)[0]
        .list.filter((o) => o.platform_id == item.platform_id)[0].disabled = false;
      // console.log(
      //   111,
      //   '1item',
      //   e.target?.checked,
      //   item.state,
      //   item,
      //   plateOptions,
      //   current_platform_ids.value,
      // );
      venueList.value.filter((item) => item.value == tabValue.value)[0][Venue_statistics.value] =
        plateOptions
          .filter((item) => item.game_type == tabValue.value)
          .filter((obj) => obj.state === 1)
          .map((el) => {
            return {
              name: el.name,
              value: el.value,
            };
          });
      // console.log(111, 'venueList.value', venueList.value);
    }, 111);
  };

  onUnmounted(() => {
    eventBus.off('change_Venue_statistics');
    eventBus.off('formChange_m');
    eventBus.off('tyChange');
  });

  async function setContentList() {
    const values = await getFieldsValue();
    const hasOriginalValue = contentList.value.some((item) => item.value === 'original');
  }
  // 全选开放所有语言
  function onCheckAllChange(e: any, model: any, field: any): void {
    Object.assign(openTerminalState, {
      checkedList: e.target.checked ? openLangOptions : [],
      indeterminate: false,
    });
    model[field] = e.target.checked ? openLangOptions : [];
  }

  function onChangeOpenTerminal(value: string[], model: any, field: any): void {
    model[field] = value;
  }
  /** 监听语言切换的变化 */
  watch(
    () => openTerminalState.checkedList,
    (newVal) => {
      openTerminalState.indeterminate =
        !!newVal.length && newVal.length < openTerminalOptions.value.length;
      openTerminalState.checkAll = newVal.length === openTerminalOptions.value.length;
      setFieldsValueLeft({ lang: openTerminalState.checkedList });
      currenyLang.value = filterHandleCurry(openTerminalState.checkedList);
      contentList.value = filterHandleCurrylang(openTerminalState.checkedList);
      pushContentList();
      console.log(detailList.value);
      detailList.value = updateObj(openTerminalState.checkedList, detailList.value);
      zxLange.value = updateObj(openTerminalState.checkedList, zxLange.value);
      btnLange.value = updateObj(openTerminalState.checkedList, btnLange.value);

      if (contentList.value.length > 0) currentLang.value = contentList.value[0];
      else currentLang.value = langList.value[0];
      currentCurryId.value = currenyLang.value[0]?.value || '701';
      changeHandleCurry(currentCurryId.value);
    },
  );

  function changeHandleCurry(value) {
    currentCurryId.value = value;
    if (defaultTy.value != 4 || defaultTy.value != 5) {
      setFieldsValueLeft({
        award: currencyNameList_award.value[currentCurryId.value]?.award || '',
      });
    }
  }

  eventBus.on('change_award', (data) => {
    if (currencyNameList_award.value[currentCurryId.value]) {
      currencyNameList_award.value[currentCurryId.value].award = data;
    } else {
      currencyNameList_award.value[currentCurryId.value] = {};
      currencyNameList_award.value[currentCurryId.value].award = data;
    }
  });
  function changInput(type) {
    if (openTerminalState.checkedList.includes(syslang)) {
      btnLange.value[syslang] = btnText.value;
    }
    if (type == 'RIGHT') setFieldsValueLeft({ button: btnText.value });
    else setFieldsValueLeft({ button: btnText.value });
  }

  /** 过滤选择的语言，筛选出对应的法币 */
  function filterHandleCurry(langArr: string | string[]) {
    return currencyList.filter((currency) => langArr.includes(currency.lang));
  }
  const [textModal, { openModal }] = useModal();

  function pushContentList() {
    contentList.value.forEach((el) => {
      detailList.value[el.value] = el.detailList;
      zxLange.value[el.value] = el.zxTransitionValue;
      btnLange.value[el.value] = el.btnTransitionValue;
    });
    // console.log('contentList.value', contentList.value);
    // console.log('zxLange.value', zxLange.value);
    // console.log('detailList.value', detailList.value);
  }
  //更多语言
  async function handleMoreLagarage(type) {
    pushContentList();
    let res = {};
    if (type == 'zh_name') {
      res = zxLange.value;
    } else if (type == 'detailList') {
      res = detailList.value;
    } else {
      res = btnLange.value;
    }
    console.log('语言列表：', res);
    openModal(true, { data: res, type });
  }

  async function validateBeforeSubmit(leftValues) {
    function checkValuesExist(obj) {
      for (let key in obj) {
        if (obj.hasOwnProperty(key) && obj[key] === '') {
          return false;
        }
      }
      return true;
    }
    // console.log('zxLange.value', zxLange.value);
    if (!checkValuesExist(zxLange.value)) {
      message.error(`配置活动名称多语言`);
      return false;
    }

    return true;
  }
  function emitsValues(value, type) {
    if (type == 'zh_name') {
      if (openTerminalState.checkedList.includes(syslang)) {
        zhText.value = value[syslang];
        setFieldsValueLeft({ zh_name: zhText.value });
      }
      zxLange.value = value;
    } else if (type == 'button_text') {
      if (openTerminalState.checkedList.includes(syslang)) {
        btnText.value = value[syslang];
        setFieldsValueLeft({ button_text: btnText.value });
      }
      btnLange.value = value;
    } else {
      if (openTerminalState.checkedList.includes(syslang)) {
        btnText.value = value[syslang];
        setFieldsValueLeft({ button_text: btnText.value });
      }
      btnLange.value = value;
    }
  }
  function filterHandleCurrylang(langArr) {
    return langList.value.filter((currency) => langArr.includes(currency.value));
  }

  function updateObj(arr, obj) {
    // 删除不在cehis1中的键
    for (const key in obj) {
      if (!arr.includes(key)) {
        delete obj[key];
      }
    }
    // 添加cehis1中缺少的键
    for (const key of arr) {
      if (!(key in obj)) {
        obj[key] = null;
      }
    }
    console.log(obj);
    return obj;
  }

  function changInputzhText(e) {
    if (e == 'detail') {
      if (openTerminalState.checkedList.includes(syslang)) {
        detailList.value[syslang] = detail.value;
      }
      // console.log('zxLange.value', zxLange.value);
      setFieldsValueLeft({ detail: detailList.value[syslang] });
    } else {
      if (openTerminalState.checkedList.includes(syslang)) {
        zxLange.value[syslang] = zhText.value;
      }
      // console.log('zxLange.value', zxLange.value);
      setFieldsValueLeft({ names: zxLange.value[syslang] });
    }
  }
  async function handleTinymceBlurZx(e) {
    if (e == 'detailList') {
      const item = contentList.value.find((el) => el.value == syslang);
      if (item?.['detailList'] != detail.value) {
        await translateContentList(contentList.value, detail.value, 0, 'detailList');
      }
    } else if (e == 'buttonText') {
      const item = contentList.value.find((el) => el.value == syslang);
      if (item?.['btnTransitionValue'] != btnText.value) {
        await translateContentList(contentList.value, btnText.value, 0, 'btnTransitionValue');
      }
    } else {
      const item = contentList.value.find((el) => el.value == syslang);
      if (item?.['zxTransitionValue'] != zhText.value) {
        await translateContentList(contentList.value, zhText.value, 0, 'zxTransitionValue');
      }
    }
    pushContentList();
  }
  eventBus.on('tyChange', (e) => {
    defaultTy.value = e || 1;
    // getMissionListData();
    if (e == 4 || e == 5) {
      if (e == 4) {
        zhText.value = '每日存款';
      } else if (e == 5) {
        zhText.value = '每日投注';
      }
      handleTinymceBlurZx('修改');
      changInputzhText('修改');
    }
  });
  eventBus.on('cycleCharge', (val) => {
    let e = defaultTy.value;
    if (val == 1) {
      if (e == 4 || e == 5) {
        if (e == 4) {
          zhText.value = '每日存款';
        } else if (e == 5) {
          zhText.value = '每日投注';
        }
      }
    } else if (val == 2) {
      if (e == 4) {
        zhText.value = '每周存款';
      } else if (e == 5) {
        zhText.value = '每周投注';
      }
    } else if (val == 3) {
      if (e == 4) {
        zhText.value = '每月存款';
      } else if (e == 5) {
        zhText.value = '每月投注';
      }
    }
    handleTinymceBlurZx('修改');
    changInputzhText('修改');
  });
  onMounted(() => {
    updateValidList();
  });
  onUnmounted(() => {
    eventBus.off('updatedailyCollectionLimit');
    eventBus.off('onRewardMethodsChange');
    eventBus.off('cycleCharge');
  });
</script>
<style lang="less" scoped>
  .ant-btn-primary[disabled] {
    background: #a2a2a2;
  }
</style>
